﻿using System;
using Cos.Core.Model.Security;
using Cos.Core.Security;
using Cos.Module.Security.Data;
using Cos.Module.Security.Exceptions;

namespace Cos.Module.Security
{
    public class UserService : IUserService
    {

        /// <summary>
        /// The security data access object
        /// </summary>
        private readonly ISecurityRepository securityRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="UserService"/> class.
        /// </summary>
        /// <param name="securityRepository">The security repository.</param>
        public UserService(ISecurityRepository securityRepository)
        {
            this.securityRepository = securityRepository;
        }

        public User Login(string userName, string password)
        {
            var user = this.securityRepository.GetUser(userName);

            if (user == null)
            {
                return null;
            }

            var passwordHash = HashHelper.GetMD5Hash(password);

            return this.securityRepository.ValidatePassword(user, passwordHash) ? user : null;
        }

        public String ForgotPassword(string userName, string email)
        {
            var user = this.securityRepository.GetUser(userName);

            if (!user.Email.Equals(email, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new InvalidUserEmailException();
            }

            // TODO Generate password
            var newPassword = Guid.NewGuid().ToString();
            var newPasswordHash = HashHelper.GetMD5Hash(newPassword);

            this.securityRepository.UpdatePassword(user, newPasswordHash);

            // TODO Send email here?
            return newPassword;
        }

        public void ChangePassword(User user, String oldPassword, String newPassword)
        {
            var oldPasswordHash = HashHelper.GetMD5Hash(oldPassword);
            var newPasswordHash = HashHelper.GetMD5Hash(newPassword);

            if (!this.securityRepository.ValidatePassword(user, oldPasswordHash))
            {
                throw new InvalidCredentialsException();
            }

            this.securityRepository.UpdatePassword(user, newPasswordHash);
        }
    }

}